package com.allwees.bs.c.module.order.context.validator;

import com.allwees.bs.c.module.order.entity.OrderEntity;
import com.allwees.bs.c.module.order.entity.OrderItemEntity;
import com.allwees.bs.c.module.product.dao.SkuDao;
import com.allwees.bs.c.module.product.entity.ProductEntity;
import com.allwees.bs.c.module.product.entity.SkuEntity;
import com.allwees.bs.c.module.product.repository.ProductRepository;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class OrderPayPreValidator {

    @Autowired
    private ProductRepository productRepository;

    @Resource
    private SkuDao skuDao;

    public void validate(List<OrderItemEntity> orderItems, OrderEntity order) {
        for (OrderItemEntity orderItem : orderItems) {
            validateProduct(orderItem.getProductUuid());
            validateSku(orderItem.getSkuUuid());
        }
        order.setOrderItems(orderItems);
    }

    private ProductEntity validateProduct(String productUuid) {
        ProductEntity product = productRepository.getByUuid(productUuid);
        if (product == null) {
            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
        }
        return  product;
    }

    private void validateSku(String skuUuid) {
        SkuEntity sku = skuDao.findByUuid(skuUuid);
        if (sku == null) {
            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
        }
    }
}
